﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpDelegateLambda
{
    /// <summary>
    /// 自定义泛型委托
    /// 使用原因：普通委托在数据类型的限定上十分严格，有时候需求变化，可能适应不了
    /// </summary>
    public class GenericDelegate
    {
        public void Test1()
        {
            //定义泛型委托变量
            MyGenericDelegate<int> myGenericDelegate1 = Add;
            MyGenericDelegate<double> myGenericDelegate2 = Sub;

            Console.WriteLine("自定义泛型委托1：10+20=" +myGenericDelegate1(10,20));
            Console.WriteLine("自定义泛型委托2：10+20=" + myGenericDelegate2(10, 20));


            //使用泛型委托：结合匿名方法
            MyGenericDelegate<int> myGenericDelegate3 = delegate (int a, int b)
            {
                return a + b;
            };

            MyGenericDelegate<double> myGenericDelegate4 = delegate (double a, double b)
            {
                return a - b;
            };

            Console.WriteLine("自定义泛型委托3：10+20=" + myGenericDelegate3(10, 20));
            Console.WriteLine("自定义泛型委托4：10+20=" + myGenericDelegate4(10, 20));

            MyGenericDelegate<int> myGenericDelegate5 = (a, b) =>  a + b;
            MyGenericDelegate<double> myGenericDelegate6 = (a, b) => a - b;
            Console.WriteLine("自定义泛型委托5：10+20=" + myGenericDelegate5(10, 20));
            Console.WriteLine("自定义泛型委托6：10+20=" + myGenericDelegate6(10, 20));

        }

        //定义方法
        public int Add(int a,int b)
        {
            return a + b;
        }

        public double Sub(double a,double b)
        {
            return a - b;
        }
    }

    //定义泛型委托
    public delegate T MyGenericDelegate<T>(T param1,T param2);
}
